package editor;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.HashMap;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Gui extends JFrame{
	
	private boolean clicked = false;
	private int elemX = 20,elemY = 20;
	private int gridX,gridY;
	private JPanel[][] grid;
	private boolean[] vectorizedOutputs;
	private JPanel cpanel = new JPanel();
	private final HashMap<Boolean, Color> colors;
	public Gui(int x, int y) {
		gridX = x;
		gridY = y;
		vectorizedOutputs = new boolean[gridX*gridY];
		init();
		setVisible(true);
		//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		colors = new HashMap<Boolean, Color>();
		colors.put(true, Color.black);
		colors.put(false, Color.white);
	}
	private void init(){
		add(cpanel);
		setSize(20*gridY,20*gridX);
		cpanel.setLayout(new GridLayout(gridX,gridY));
		grid = new JPanel[gridX][gridY];
		for(int i=0;i < gridX;i++){
			for(int j=0;j < gridY;j++){
				grid[i][j] = new JPanel();
				grid[i][j].setSize(elemX, elemY);
				grid[i][j].setBackground(Color.white);
				final JPanel me =grid[i][j]; 
				grid[i][j].addMouseListener(new MyMouseListener(me,i*gridY+j));
				cpanel.add(grid[i][j]);
			}	
		}
	}
	public boolean[] getOutput(){
		return vectorizedOutputs;
	}
	public void setDisplay(int index, boolean val){
		vectorizedOutputs[index] = val;
		int x = index/gridY;
		int y = index%gridY;
		((MyMouseListener)grid[x][y].getMouseListeners()[0]).update();
	}
	public static void main(String[] args) {
		int x = Integer.parseInt(args[0]);
		int y = Integer.parseInt(args[1]);
		Gui g = new Gui(x,y);
	}
	private class MyMouseListener implements MouseListener{
		private JPanel me;
		private int pos;
		public MyMouseListener(JPanel mee,int poss) {
			me = mee;
			pos = poss;
		}
		public void mouseClicked(MouseEvent arg0) {
			// TODO Auto-generated method stub
			
		}
		public void mouseEntered(MouseEvent arg0) {
			// TODO Auto-generated method stub
			if(clicked) {
				vectorizedOutputs[pos] = !vectorizedOutputs[pos];
				update();
			}
		}
		public void mouseExited(MouseEvent arg0) {
			
		};
		public void mousePressed(MouseEvent arg0) {
			// TODO Auto-generated method stub
			clicked = true;
			vectorizedOutputs[pos] = !vectorizedOutputs[pos];
			update();
		}
		public void mouseReleased(MouseEvent arg0) {
			// TODO Auto-generated method stub
			clicked = false;
			update();
		}
		private void update(){
			me.setBackground(colors.get(vectorizedOutputs[pos]));
		}
	}
}

